import gdata.spreadsheet.service
import gdata.docs.data
import gdata.docs.client
import os, sys
from getpass import getpass
from optparse import OptionParser
from sched_db.importlib import *
from sched_db.create import *
from sched_db import *

p = OptionParser()
p.add_option('-u', dest="username", default="schedule.uoit@gmail.com",
             help="Google account name")
p.add_option("-p", dest="password", help="Google account password")
p.add_option("-f", dest="dbfile", help="Database file")
p.add_option("-s", dest="semester", help="Semester [YYYYMM]")
p.add_option("--clear", dest="clear", default=False,
             action="store_true",
             help="Clear database before import")
(opt, args) = p.parse_args()

if not opt.semester:
  print "Requires -s"
  p.print_help()
  sys.exit(0)

if not opt.dbfile:
  opt.dbfile = "%s.sqlite" % opt.semester
  print "Saving database to %s" % opt.dbfile

if not opt.password:
  opt.password = getpass("Password:")

if not os.path.exists(opt.dbfile):
  create_tables(opt.dbfile)
else:
  if opt.clear:
    delete_tables(opt.dbfile)
    create_tables(opt.dbfile)

spread = gdata.spreadsheet.service.SpreadsheetsService()
spread.source = "uoit schedule database"
spread.email = opt.username
spread.password = opt.password
spread.ProgrammaticLogin()

doc = gdata.docs.client.DocsClient()
doc.ClientLogin(opt.username, opt.password, spread.source)

# Get the spreadsheet keys
# Look for "<semester> Banner" and "<semester> Conflicts"

docfeed = doc.GetDocList(uri="/feeds/default/private/full")
dockeys = dict()
lookfor = ["Banner", "Conflicts", 'Locations']
for f in docfeed.entry:
  title = f.title.text
  key = f.id.text.split("/")[-1].split("%3A")[-1]
  for doctype in lookfor:
    if title == '%s %s' % (opt.semester, doctype):
      dockeys[doctype] = key

# Perform data imports

def clean(x):
  return "" if x == None else x.strip()

def tuples(key):
  wsfeed = spread.GetWorksheetsFeed(key)
  wskey = wsfeed.entry[0].id.text.split("/")[-1]
  datafeed = spread.GetListFeed(key, wskey)
  for row in datafeed.entry:
	yield dict((x, clean(row.custom[x].text)) for x in row.custom.keys())

if "Banner" in dockeys:
  print "Importing banner"
  import_banner(opt.dbfile, opt.semester, tuples(dockeys["Banner"]))
else:
  print "Banner is not present in the cloud"

if "Conflicts" in dockeys:
  print "Importing conflicts"
  import_conflicts(opt.dbfile, opt.semester, tuples(dockeys["Conflicts"]))

if 'Locations' in dockeys:
  print "Importing locations"
  import_locations(opt.dbfile, opt.semester, tuples(dockeys['Locations']))

build_starttimes(opt.dbfile)
build_freerooms(opt.dbfile, opt.semester)
print "Building conflict-schedule view"
build_conflictview(opt.dbfile, opt.semester)
